package danlib;

import java.io.*;

import javax.sound.sampled.*;
import java.lang.*;
import java.net.*;

public class DSound
{
	Clip[] clips;
	int on = 0;
	public DSound( String name )
	{
		clips = new Clip[5];
		try
		{
			
			File file;
			try
			{
				file = new File(name);
				for( int i = 0; i < clips.length; i++ )
				{
					AudioInputStream stream = AudioSystem.getAudioInputStream(file);
					DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat());
					clips[i] = setUp( info, stream );
					stream.close();
				}
			}
			catch( Exception ex )
			{
				URL u = this.getClass().getResource(name);
				for( int i = 0; i < clips.length; i++ )
				{
					AudioInputStream stream = AudioSystem.getAudioInputStream(u);
					DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat());
					clips[i] = setUp( info, stream );
					stream.close();
				}
			}
			
			
			
		}
		catch( Exception ex )
		{
			ex.printStackTrace();
		}

	}
	
	public DSound( String name, int repeats )
	{
		clips = new Clip[repeats];
		try
		{
			AudioInputStream stream = AudioSystem.getAudioInputStream(new File(name));
			DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat());
			for( int i = 0; i < clips.length; i++ )
			{
				clips[i] = setUp( info, stream );
			}
			stream.close();
			
		}
		catch( Exception ex )
		{
			ex.printStackTrace();
		}

	}
	
	public Clip setUp( DataLine.Info info, AudioInputStream stream ) throws Exception
	{
		Clip clip = (Clip) AudioSystem.getLine(info);
		clip.open(stream);
		return clip;
	}
	
	public void play()
	{
		try
		{
			Clip clip = clips[on];
			clip.stop();
			clip.setFramePosition(0);
			clip.start();
			on = (on + 1) % clips.length;
		}
		catch( Exception ex )
		{
			ex.printStackTrace();
		}
	
	}
	
	public void play(int i)
	{
		try
		{
			int a = i;
			if( i == -1 )
			{
				a = Clip.LOOP_CONTINUOUSLY;
			}
			Clip clip = clips[on];
			clip.stop();
			clip.setFramePosition(0);
			clip.loop(a);
			on = (on + 1) % clips.length;
		}
		catch( Exception ex )
		{
			ex.printStackTrace();
		}
	
	}
	
	

}